<!-- 任务详情页面 -->
<template>
  <div>
    <div class="div_box">
      <div style="min-width: 1600px;">
        <el-row :gutter="5">
          <el-col :span="1"><el-tag type="info">任务名称</el-tag></el-col>
          <el-col :span="2"><el-tag class="titleValue" type="success">{{ taskSummary.name }}</el-tag></el-col>
          <el-col :span="1"><el-tag type="info">任务作者</el-tag></el-col>
          <el-col :span="2"><el-tag class="titleValue" type="success">{{ taskSummary.creator }}</el-tag></el-col>
          <el-col :span="1"><el-tag type="info">任务描述</el-tag></el-col>
          <el-col :span="2"><el-tag class="titleValue" type="success"><el-input v-model="taskSummary.description" class="el-tag-input" /></el-tag></el-col>
        </el-row>
        <el-row :gutter="5">
          <el-col :span="1"><el-tag type="info">启动时间</el-tag></el-col>
          <el-col :span="2"><el-tag class="titleValue" type="success"><el-input v-model="taskSummary.rampTime" class="el-tag-input" /></el-tag></el-col>
          <el-col :span="1"><el-tag type="info">执行时间</el-tag></el-col>
          <el-col :span="2"><el-tag class="titleValue" type="success"><el-input v-model="taskSummary.duration" class="el-tag-input" /></el-tag></el-col>
        </el-row>
        <el-row :gutter="5" style="margin-top: 20px;">
          <el-button size="mini" icon="el-icon-video-play" title="批量执行选中脚本或场景" circle @click="startTask()" />
          <el-button size="mini" icon="el-icon-refresh" title="刷新" circle @click="updateTaskSummary" />
          <el-button size="mini" icon="el-icon-delete" title="删除任务" circle @click="todo" />
          <el-button size="mini" icon="el-icon-upload2" title="快捷上传脚本" circle @click="uploadScriptHandle()" />
          <el-button size="mini" icon="el-icon-edit" title="编辑任务" circle @click="modifyTaskHandle()" />
        </el-row>
      </div>
    </div>
    <div class="div_box">
      <div style="min-width: 1600px;">
        <el-collapse v-model="activeNames" @change="handleChange">
          <!-- 脚本：查看、编辑、执行、资源文件配置、查看报告 -->
          <el-collapse-item name="1">
            <template slot="title">
              <div style="margin-left: 10px; font-size: 20px; color: #eb6709;">
                <svg-icon icon-class="script" />
                <span style="margin-left: 16px;">脚本</span>
              </div>
            </template>
            <div class="collapse-item-dev">
              <el-table v-loading="scriptTableLoading" :data="taskScripts" max-height="400" style="width: 100%" @selection-change="selectionScriptChangeHandle">
                <el-table-column type="selection" header-align="center" align="center" width="50" />
                <el-table-column prop="scriptName" header-align="center" label="脚本名称" width="180" sortable />
                <el-table-column header-align="center" align="center" label="依赖资源">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.resourceIds" multiple filterable allow-create default-first-option placeholder="请选择资源标签" @visible-change="scriptChangeSwitch($event, scope.row)" @change="scriptChange(scope.row)">
                      <el-option v-for="item in selectResourceListOption" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="预设并发" header-align="center" width="200">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.users" size="small" controls-position="right" :min="1" :max="30000" label="执行时限定的并发值" @change="scriptUsersChange(scope.row)" />
                  </template>
                </el-table-column>
                <el-table-column label="预设QPS" header-align="center" width="200">
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.qps" size="small" controls-position="right" :min="0" :max="1000000" label="执行时限定的最大QPS" @change="scriptQpsChange(scope.row)" />
                  </template>
                </el-table-column>
                <el-table-column label="备注信息" header-align="center" width="200">
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.remark" placeholder="额外的备注信息" />
                  </template>
                </el-table-column>
                <el-table-column label="压测平台" header-align="center" width="200" sortable prop="platform">
                  <template slot-scope="scope">
                    <svg-icon v-if="scope.row.platform == 'JMETER'" icon-class="jmeter-logo" class="platformIcon" />
                    <svg-icon v-if="scope.row.platform == 'GATLING'" icon-class="gatling-logo" class="platformIcon" />
                  </template>
                </el-table-column>
                <el-table-column fixed="right" header-align="center" label="操作">
                  <template slot-scope="scope">
                    <el-row>
                      <el-button type="text" size="small" @click="viewScriptHandle(scope.row)">查看</el-button>
                      <el-button type="text" size="small" @click="editScriptHandle(scope.row)">编辑</el-button>
                      <el-button type="text" size="small" @click="removeScriptSingle(scope.row)">删除</el-button>
                    </el-row>
                    <el-row>
                      <el-button type="text" size="small" @click="runSingle(scope.row)">执行</el-button>
                      <el-button type="text" size="small" @click="getTaskScriptReports(scope.row)">报告</el-button>
                      <el-button type="text" size="small" @click="modifyTaskHandle">新增</el-button>
                    </el-row>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
          <el-collapse-item name="2">
            <template slot="title">
              <div style="margin-left: 10px; font-size: 20px; color: #eb6709;">
                <svg-icon icon-class="report" />
                <span style="margin-left: 16px;">报告</span>
              </div>
            </template>
            <div class="collapse-item-dev">
              <el-table v-loading="reportTableLoading" :data="taskReports" max-height="400" style="width: 100%">
                <el-table-column prop="scriptName" label="脚本名称" width="180" sortable />
                <el-table-column prop="qps" label="QPS" width="180" />
                <el-table-column prop="startTimeStr" label="开始时间" width="180" sortable />
                <el-table-column prop="endTimeStr" label="结束时间" width="180" sortable />
                <el-table-column prop="remark" label="备注" width="180" />
                <el-table-column prop="percentAge" header-align="center" align="center" label="执行进度" sortable width="300">
                  <template slot-scope="scope">
                    <el-popover trigger="hover" placement="top">
                      <p>限定QPS为: {{ scope.row.qps }}</p>
                      <div slot="reference" class="name-wrapper">
                        <el-progress v-if="scope.row.status === 'RUNNING' || scope.row.status === 'FINISHED'" :text-inside="true" :stroke-width="18" :percentage="scope.row.percentAge" status="success" />
                        <span v-if="scope.row.status === 'WAITING' || scope.row.status === 'STOPPED' || scope.row.status === 'ERROR'">{{ scope.row.status }}</span>
                      </div>
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column fixed="right" label="操作">
                  <template slot-scope="scope">
                    <el-button type="text" size="small" @click="getReportDetail(scope.row)">详情</el-button>
                    <el-button v-if="scope.row.status === 'RUNNING'" type="text" size="small" @click="stopTask(scope.row)">停止</el-button>
                    <el-button v-if="scope.row.status === 'WAITING' || scope.row.status === 'FINISHED' || scope.row.status === 'STOPPED' || scope.row.status === 'ERROR'" type="text" size="small" @click="deleteReport(scope.row)">删除</el-button>
                    <el-button type="text" size="small" @click="reExecution(scope.row)">重试</el-button>
                    <el-button type="text" size="small" @click="editScriptHandle(scope.row)">脚本</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </div>
    <el-dialog
      title="QPS & 报告备注"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="reExecutionform" label-position="left" label-width="60px">
        <el-form-item label="并发">
          <el-input v-model="reExecutionform.users" placeholder="指定并发，不填则保持不变" />
        </el-form-item>
        <el-form-item label="QPS">
          <el-input v-model="reExecutionform.qps" placeholder="指定QPS，不填则保持不变" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="reExecutionform.remark" placeholder="报告执行备注信息，不填则为NA" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">确认</el-button>
          <el-button @click="dialogVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 上传脚本 -->
    <upload-script ref="uploadScript" @reflushDataList="init()" />
    <!-- 查看脚本 -->
    <view-script ref="viewScript" @reflushDataList="init()" />
    <!-- 编辑脚本 -->
    <edit-script ref="editScript" @reflushDataList="init()" />
    <!-- 启动任务 -->
    <task-start ref="taskStart" @reflushDataList="init()" />
    <!-- 任务编辑 -->
    <task-modify ref="taskModify" @reflushDataList="init()" />
  </div>
</template>

<script>
import { search, updateTaskSummary, getScripts, findReports, findScriptReports, taskRemoveScripts, updateScriptUsersOrQps } from '@/api/perf/task.js'
import { deleteReport, stop, reExecution } from '@/api/perf/report.js'
import { updateResource } from '@/api/perf/script.js'
import { getAllNames } from '@/api/perf/resource.js'
import UploadScript from './script-upload'
import ViewScript from './script-view'
import EditScript from './script-edit'
import TaskStart from './task-start'
import TaskModify from './task-modify'
export default {
  'name': 'PerfTaskDetail',
  components: {
    UploadScript,
    ViewScript,
    EditScript,
    TaskStart,
    TaskModify
  },
  data() {
    return {
      currentPath: this.$route.fullPath,
      taskId: null,
      scriptTableLoading: false,
      reportTableLoading: false,
      activeNames: ['1', '2'],
      taskSummary: {},
      taskScripts: [],
      taskReports: [],
      selectionScript: [],
      dialogVisible: false,
      reExecutionform: {},
      selectResourceListOption: [],
      timer: null,
      scriptReport: null
    }
  },
  watch: {
    taskSummary(newValue, oldValue) {
      const that = this
      this.$store.state.tagsView.visitedViews.forEach(function(tag) {
        if (tag.fullPath === that.currentPath) {
          tag.title = '性能任务：' + newValue.name
        }
      })
    }
  },
  created() {
    this.taskId = this.$route.params.taskId
    this.init()
    // 这里用that，要不在setInterval中访问不到this
    const that = this
    this.timer = setInterval(function() {
      that.getTaskReports()
    }, 1000)
  },
  activated() {
    this.init()
  },
  destroyed() {
    clearInterval(this.timer)
  },
  methods: {
    todo() {
      this.$message.info('todo')
      console.info(this.taskSummary)
    },
    updateTaskSummary() {
      // 更新taskSummary信息
      const data = {
        'taskId': this.taskId,
        'description': this.taskSummary.description ? this.taskSummary.description : 'REPLACE ME',
        'rampTime': this.taskSummary.rampTime ? this.taskSummary.rampTime : 60,
        'duration': this.taskSummary.duration ? this.taskSummary.duration : 600
      }
      updateTaskSummary(data).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$message.success(respnose.message)
          this.init()
        } else {
          this.$message.error(respnose.message)
        }
      })
    },
    init() {
      this.getAllNames()
      this.getTaskSummary()
      this.getTaskScripts()
      this.scriptReport = null
      this.getTaskReports()
    },
    handleChange(val) {},
    getTaskSummary() {
      const taskSearchForm = { 'taskId': this.taskId }
      search(taskSearchForm).then(respnose => {
        if (respnose && respnose.code === 200) {
          const { data } = respnose
          this.taskSummary = data
        } else {
          this.$message.error(respnose.message)
        }
      })
    },
    getTaskScripts() {
      this.scriptTableLoading = true
      getScripts(this.taskId).then(respnose => {
        if (respnose && respnose.code === 200) {
          const { data } = respnose
          this.taskScripts = data
        } else {
          this.$message.error(respnose.message)
        }
        this.scriptTableLoading = false
      })
    },
    getTaskReports() {
      // TODO 暂时不做分页
      if (this.scriptReport) {
        findScriptReports(this.taskId, this.scriptReport, 1, 100000).then(respnose => {
          if (respnose && respnose.code === 200) {
            const { data } = respnose
            this.taskReports = data.content
          } else {
            this.$message.error(respnose.message)
          }
        })
      } else {
        findReports(this.taskId, 1, 100000).then(respnose => {
          if (respnose && respnose.code === 200) {
            const { data } = respnose
            this.taskReports = data.content
          } else {
            this.$message.error(respnose.message)
          }
        })
      }
    },
    getTaskScriptReports(row) {
      this.scriptReport = row.scriptId
      this.getTaskReports()
    },
    startTaskHandle(row) {
      this.$nextTick(() => {
        this.$refs.taskStart.initDialog(row.scriptId)
      })
    },
    // 查看脚本
    viewScriptHandle(row) {
      this.$nextTick(() => {
        this.$refs.viewScript.init(row.scriptId)
      })
    },
    // 编辑脚本
    editScriptHandle(row) {
      this.$nextTick(() => {
        this.$refs.editScript.init(row.scriptId)
      })
    },
    // 删除单个脚本
    removeScriptSingle(row) {
      const data = {
        'taskId': this.taskId,
        'scripts': []
      }
      data.scripts.push(row.scriptId)
      taskRemoveScripts(data.taskId, data.scripts.join(',')).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$message.success(respnose.message)
          this.getTaskScripts()
        } else {
          this.$message.error(respnose.message)
        }
      })
    },
    // 编辑任务
    modifyTaskHandle() {
      this.$nextTick(() => {
        this.$refs.taskModify.init(this.taskId)
      })
    },
    // 上传脚本
    uploadScriptHandle() {
      this.$nextTick(() => {
        this.$refs.uploadScript.init()
      })
    },
    // 脚本列表多选
    selectionScriptChangeHandle(val) {
      this.selectionScript = val
    },
    runSingle(row) {
      const data = [row.scriptId]
      this.$nextTick(() => {
        this.$refs.taskStart.init(this.taskId, data)
      })
    },
    startTask() {
      if (this.selectionScript.length === 0) {
        this.$message.warning('请至少选择一个脚本')
        return
      }
      const data = this.selectionScript.map(o => {
        return o.scriptId
      })
      this.$nextTick(() => {
        this.$refs.taskStart.init(this.taskId, data)
      })
    },
    // 显示报告详情
    getReportDetail(row) {
      // 这里不要删除缓存了
      // this.$store.dispatch('tagsView/delView', { name: 'PerfReportDetail', path: '/perf/perf-report-detail' })
      this.$nextTick(() => {
        this.$router.push({
          name: 'PerfReportDetail',
          params: {
            reportId: row.id
          }
        })
      })
    },
    // 删除报告
    deleteReport(row) {
      deleteReport(row.id).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$message.success(respnose.message)
          this.getTaskReports()
        } else {
          this.$message.error(respnose.message)
        }
      })
    },
    // 停止任务
    stopTask(row) {
      stop(row.id).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$message.success(respnose.message)
          this.getTaskReports()
        } else {
          this.$message.error(respnose.message)
        }
      })
    },
    // 重新开始任务
    reExecution(row) {
      this.reExecutionform = { reportId: row.id }
      this.dialogVisible = true
    },
    onSubmit() {
      if (!this.reExecutionform.remark) {
        this.reExecutionform.remark = 'NA'
      }
      if (this.reExecutionform.qps === null || !(this.reExecutionform.qps > 0)) {
        this.reExecutionform.qps = 0
      }
      if (this.reExecutionform.users === null || !(this.reExecutionform.users > 0)) {
        this.reExecutionform.users = 0
      }
      reExecution(this.reExecutionform.reportId, this.reExecutionform.users, this.reExecutionform.qps, this.reExecutionform.remark).then(respnose => {
        if (respnose && respnose.code === 200) {
          this.$message.success(respnose.message)
          this.getTaskReports()
          this.dialogVisible = false
        } else {
          this.$message.error(respnose.message)
        }
      })
    },
    getAllNames() {
      getAllNames().then(respnose => {
        if (respnose && respnose.code === 200) {
          this.selectResourceListOption = respnose.data
        } else {
          this.$message.error(respnose.message)
        }
      })
    },
    // 控制要不要更新关联数据
    scriptChangeSwitch(event, row) {
      row.isActivity = event
    },
    // 更新关联数据操作
    scriptChange(row) {
      if (row.isActivity) {
        updateResource(row.scriptId, row.resourceIds.join(',')).then(respnose => {
          if (respnose && respnose.code === 200) {
            this.$message.success(respnose.data)
          } else {
            this.$message.error(respnose.message)
          }
        })
      }
    },
    scriptUsersChange(row) {
      updateScriptUsersOrQps(this.taskId, row.scriptId, 'users', row.users).then(response => {
        if (response && response.code === 200) {
          this.$message.success(response.data)
        } else {
          this.$message.error(response.message)
        }
      })
    },
    scriptQpsChange(row) {
      updateScriptUsersOrQps(this.taskId, row.scriptId, 'qps', row.qps).then(response => {
        if (response && response.code === 200) {
          this.$message.success(response.data)
        } else {
          this.$message.error(response.message)
        }
      })
    },
    handleClose(done) { done() }
  }
}
</script>

<style scoped="scoped">
.titleValue {
  width: 90%;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space: nowrap;
}
.div_box {
  border: 1px solid #eee;
  padding-left: 15px;
  padding-right: 15px;
  padding-top: 15px;
  padding-bottom: 10px;
  margin-top: 10px;
  margin-bottom: 10px;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  overflow-x: auto;
}
.el-row {
  padding-top: 3px;
  padding-bottom: 3px;
}
.el-tag {
  width: 100%;
}
.platformIcon {
  width: 8em;
  height: 2em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}
</style>
<style>
  /* 控制el-tag下面的input样式 */
  .el-tag-input input {
    border: none;
    background: #e7faf0;
    font-size: 12px;
    color: #3dce96;
    padding: 0;
    margin-top: -10px;
  }
</style>
